package com.jomoo.css.common.core.hibernate.identifier;

import org.hibernate.MappingException;
import org.hibernate.engine.spi.SessionImplementor;
import org.hibernate.id.enhanced.TableGenerator;
import org.hibernate.service.ServiceRegistry;
import org.hibernate.type.LongType;
import org.hibernate.type.Type;

import java.io.Serializable;
import java.util.Properties;

public class Ling2IdGenerator extends TableGenerator {

    public static final String STRATEGY_NAME = "com.jomoo.css.common.hibernate.identifier.Ling2IdGenerator";
    Type oritype;

    public void configure(Type type, Properties params, ServiceRegistry serviceRegistry) throws MappingException {
        params.put(TABLE_PARAM, "TBL_SEQUENCE");
        params.put(VALUE_COLUMN_PARAM, "value");
        params.put(SEGMENT_COLUMN_PARAM, "type");
        params.put(SEGMENT_VALUE_PARAM, params.get("pkColumnValue"));
        oritype = type;
        super.configure(new LongType(), params, serviceRegistry);
    }

    public synchronized Serializable generate(final SessionImplementor session, Object obj) {
        Serializable value = super.generate(session, obj);
        if (oritype.getReturnedClass() == String.class) {
            return value.toString();
        }
        return value;
    }
}
